package com.datastructures2.背包队列栈;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author MaoLin Wang
 * @date 2020/2/2821:26
 */
public class Queue<Item> implements Iterable<Item> {
    private Node<Item> first;
    private Node<Item> last;
    private int size;

    private static class Node<Item> {
        private Item item;
        private Node<Item> next;

        @Override
        public String toString() {
            return "Node{" +
                    "item=" + item +
                    ", next=" + next +
                    '}';
        }
    }
    public void enqueue(Item item){
        if (isEmpty()){
            first=new Node<>();
            first.item=item;
            last=first;
        }else {
            Node<Item>oldLast=last;
            last=new Node<>();
            last.item=item;
            oldLast.next=last;
        }
        ++this.size;
    }

    public Item dequeue(){
        if (isEmpty()){
            return null;
        }else {
            Node<Item>old=first;
            first=first.next;
            --this.size;
            return old.item;
        }
    }
    public boolean isEmpty(){
        return first==null;
    }

    public int size(){
        return this.size;
    }

    private class ListIterator<Item> implements Iterator<Item> {

        private Node<Item> current;

        public ListIterator(Node<Item> current) {
            this.current = current;
        }

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            if (!hasNext()) {
                throw new NoSuchElementException("没有元素");
            } else {
                Item item = current.item;
                current = current.next;
                return item;
            }
        }
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<>(this.first);
    }

    public static void main(String[] args) {
        Queue<Integer>queue=new Queue<>();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);
        Iterator<Integer> iterator = queue.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        Integer i = queue.dequeue();
        System.out.println(i);
        System.out.println(queue.size());
    }
}
